import React, { useEffect, useState } from 'react'

export type BackToTopProps = {
  bgColor?: string
  size?: number // 宽高，px
  threshold?: number // 多少 scrollY 后显示
  bottom?: number // 距底部 px
  right?: number // 距右侧 px
  borderRadius?: number // 圆角 px
  zIndex?: number
  text?: string
}

const BackToTop: React.FC<BackToTopProps> = ({
  bgColor = 'rgb(229, 80, 26)',
  size = 44,
  threshold = 240,
  bottom = 100,
  right = 16,
  borderRadius = 999,
  zIndex = 1000,
  text,
}) => {
  const [visible, setVisible] = useState(false)

  useEffect(() => {
    const onScroll = () => {
      setVisible(window.scrollY >= threshold)
    }
    onScroll()
    window.addEventListener('scroll', onScroll, { passive: true })
    return () => window.removeEventListener('scroll', onScroll)
  }, [threshold])

  const scrollTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' })
  }

  const style: React.CSSProperties = {
    position: 'fixed',
    right,
    bottom,
    width: size,
    height: size,
    borderRadius,
    background: bgColor,
    color: '#fff',
    display: visible ? 'flex' : 'none',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    boxShadow: '0 6px 16px rgba(0,0,0,0.15)',
    zIndex,
    userSelect: 'none',
  }

  return (
    <div role="button" aria-label="back-to-top" onClick={scrollTop} style={style}>
      {text ? (
        <span style={{ fontSize: 12, padding: '0 6px' }}>{text}</span>
      ) : (
        // 简单箭头图形
        <svg width={Math.round(size * 0.5)} height={Math.round(size * 0.5)} viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <polyline points="18 15 12 9 6 15" />
        </svg>
      )}
    </div>
  )
}

export default BackToTop

